<script setup>
import {ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
import {add{{ class_name }}, get{{ class_name }}ById, update{{ class_name }}} from "@/api/{{ table_name }}.js";

//有id是编辑，没有id是添加
const {id} = defineProps({
  id: {
    type: Number,
    default: undefined
  },
})

onMounted(() => {
  if (id !== undefined) {
    getInfo(id)
  }
})

//获取{{ table_comment }}信息
const getInfo = async (id) => {
  const {code, data, msg} = await get{{ class_name }}ById(id);
  if (code !== 200) {
    ElMessage.error(msg)
    window.location.reload();
    return
  }
  form.value = data
}

//表单
const form = ref({
  {% for column in columns %}{{ column[0] }}: undefined,
  {% endfor %}})

//提交表单
const onSubmit = async () => {
  if (id === undefined) {
    await add()
  } else {
    await edit(id)
  }
}

const emit = defineEmits(['success'])

//添加{{ table_comment }}
const add = async () => {
  const {code, msg} = await add{{ class_name }}(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}

//修改{{ table_comment }}
const edit = async () => {
  const {code, msg} = await update{{ class_name }}(form.value);
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  ElMessage.success(msg)
  emit('success')
}
</script>

<template>
  <el-form label-width="100px">{% for column in columns %}{% if column[0] != 'id' and column[0] != 'createdTime' and column[0] != 'updatedTime' %}
    <el-form-item required label="{{ column[8] or column[0] }}">{% raw %}<el-input v-model="form.{% endraw %}{{ column[0] }}{% raw %}"></el-input>{% endraw %}</el-form-item>{% endif %}{% endfor %}
  </el-form>
  <div style="text-align: right; margin-top: 20px">
    <el-button type="primary" @click="onSubmit">提交</el-button>
  </div>
</template>

<style scoped lang="scss">

</style> 